const loadCours = require('load.js');
const userModule = require('../../utils/usermodule.js');
const reloadStudy = new userModule().reloadStudy;
let optReduceTime;

const appGlobalData = getApp().globalData;
const initStudy = require('./func/initStudy.js');

Page({

  /**
   * 页面的初始数据
   */
  data: {
    page: 'make rdv',
    test: false,
    checkout: false, // 显示支付
    optDate: 0, // 初始的日期偏差值,day7传回日期，父组件使用偏差控制日期
    activeDate: null,
    chooseArray: [],
    clearTimeblockChoose: false, // 清除timeblock事件
    notionText: '确认选课',
    time: [],
    userSubject: null, // 用户目前的对应科目，目前假设只为科目2
    optionDirty: false,
    daojishi: null,
    daojishiStr: '15:00',
    askBuyCoach: false, // 判断用户有没有购买教练课程
    filterDeal: 'time',
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    initStudy(this);
  },

  onHide: function () {
    clearInterval(optReduceTime);
    this.setData({
      daojishi: null,
      daojishiStr: '15:00',
      checkout: false,
      chooseArray: [],
      notionText: '确认选课',
    })
  },

  onUnload: function () {
    if (optReduceTime) {
      clearInterval(optReduceTime);
    }
  },
  firstStep() {
    // 1-科目一，2-科目二，3科三，4-科四，5-毕业，10-报名成功，11-完成体检，12-面签,13-预约科目
    const appData = getApp().globalData.userInfo;
    const studyState = appGlobalData.userStudyInfo;
    if (!studyState || studyState.subject === 0) {
      // if (!studyState || studyState.subject === 0 || studyState.subject === 10) {
      // 空白页面
      this.setData({
        askBuyCoach: true,
      })
      return;
    }
    this.subjectWays(studyState.subject);

    const rdv = wx.getStorageSync('rdvpage2');
    if (rdv) {
      wx.removeStorage({
        key: 'rdvpage2',
      })
      this.selectComponent('#navhead').changeTitle({
        currentTarget: {
          dataset: {
            text: '已约',
          }
        }
      })
    };
  },
  loadCourPrice() {
    loadCours.getSplitPrice()
      .then(d => {
        // console.log(d);
        if (d.data.code === 0) {
          this.setData({
            courPrice: parseFloat(d.data.data),
          })
        } else {
          wx.showModal({
            title: '错误',
            content: '课程价格获取错误，将不能约课',
            showCancel: false,
            confirmText: '确定',
            confirmColor: '',
          })
        }
      })
      .catch(err => {
        console.warn(err);
      })
  },
  subjectWays(subject) { // 根据学员科目做不同的处理
    const sub = subject.toString();
    this.setData({ // 设置学员科目进入data
      userSubject: sub,
    })
    if (sub == '1' || sub == '10' || sub === '11' || sub === '12' || sub === '13') {
      // 科目1的步骤
      this.selectComponent('#progess').setState(sub);
    } else if (sub === '2' || sub === '3') {
      this.loadCourPrice();
      this.makeKechengbiao();
      wx.removeStorageSync('subjectprogress');
    }
  },
  makeKechengbiao: function () { // 创建课程表
    if (getApp().globalData.userInfo)
      // wx.showLoading({
      //   title: '读取信息',
      // });
      // 如果没有激活日，设置激活日为今天
      if (!this.data.activeDate) {
        const day = new Date();
        this.setData({
          activeDate: day.getFullYear() + '-' + this.numberToText((day.getMonth() + 1)) + '-' + this.numberToText(day.getDate())
        })
      }
    loadCours.paikeCapacity()
      .then(res => {
        console.log(res);
        this.setData({
          kemu: res
        });
        return loadCours.listPlanVo();
      })
      .then((res) => { this.renderTimeblock(res); })
      .catch(e => {
        console.error(e);
      })
  },
  renderTimeblock: function (res) { // 创建完整课程表结构
    let day7 = [];
    const now = Date.now();
    for (let i = 0; i < 7; i++) {
      const day = new Date(now + i * 24 * 60 * 60 * 1000);
      let o = {
        date: day.getFullYear() + '-' + this.numberToText((day.getMonth() + 1)) + '-' + this.numberToText(day.getDate()),
        total: '休',
      }
      let _cnDay;
      switch (day.getDay()) {
        case 3:
          _cnDay = '周三';
          break;
        case 4:
          _cnDay = '周四';
          break;
        case 5:
          _cnDay = '周五';
          break;
        case 6:
          _cnDay = '周六';
          break;
        case 0:
          _cnDay = '周日';
          break;
        case 1:
          _cnDay = '周一';
          break;
        case 2:
          _cnDay = '周二';
          break;
      }
      o.day = _cnDay;
      day7.push(o);
    }
    // console.log(day7, 'day7');
    // 生成课程表 元素为名字为 cour2018-12-01id1，无状态信息
    let kechengbiao = {};
    for (let j of day7) {
      for (let i of this.data.kemu) {
        kechengbiao['cour' + j.date + 'id' + i.id] = {
          id: i.id,
          beginEnd: i.beginEnd,
          timeStr: i.timeStr,
          status: '2',
          choose: 'n',
          date: j.date,
          reason: '未排课',
          day: j.day,
          rdvByMe: false,
        }
      }
    }
    /// 生成休息日提示
    // console.log(day7, res)
    for (let i of res) {
      for (let j of day7) {
        if (i.date === j.date) {
          j.total = 0;
        }
      }
    }
    ///
    this.setData({
      kechengbiao: kechengbiao,
      dateStruct: day7,
    })
    const _tmp = this.data.kechengbiao;
    console.log('可以使用的时间', res); // 用来设置选择状态
    for (let i of res) {
      if (i.subject.toString() === this.data.userSubject) {
        let testId = 'cour' + i.date + 'id' + i.bid;
        const t = _tmp[testId];
        if (t) {
          if (i.status == 1) {
            t.status = '1';
            t.courId = i.id;
          } else if (i.status == 2) {
            t.reason = '被约';
          } else if (i.status == 3) {
            t.status = '3';
            t.reason = '已约';
          }
        }
      }
    };
    this.setData({
      kechengbiao: _tmp,
    })
    // 需要把今天已过期过滤掉
    let beginfilter = 8;
    let endfilter = parseInt((new Date()).getHours());
    let expireList = [];
    for (let i = beginfilter; i <= endfilter; i++) {
      let test = i > 9 ? i : '0' + i;
      test += ':00';
      let _testDate = new Date();
      let _month = _testDate.getMonth() + 1;
      let _date = _testDate.getDate() > 9 ? _testDate.getDate() : '0' + _testDate.getDate();
      let testDate = _testDate.getFullYear() + '-' + (_month > 9 ? _month : '0' + _month) + '-' + _date;
      expireList.push({
        time: test,
        date: testDate,
      })
    }
    for (let i of expireList) {
      for (let j in _tmp) {
        if (_tmp[j].timeStr === i.time && _tmp[j].date === i.date && _tmp[j].status.toString() === '1') {
          _tmp[j].status = '2';
          _tmp[j].reason = '过期';
        }
      }
    }
    /// 当前日的课程表
    this.inputActiveDateBlock();
  },
  inputActiveDateBlock() { // 输入激活日课程
    let activeBlock = [];
    for (let i of this.data.kemu) {
      activeBlock.push(this.data.kechengbiao['cour' + this.data.activeDate + 'id' + i.id]);
    };
    this.setData({
      time: activeBlock, // 显示时间单元格为当课程表当前日
    });
  },
  numberToText(num) {
    if (num < 10) {
      return '0' + num.toString();
    }
    return num.toString();
  },
  changePage: function (e) { // 切换页面
    if (this.data.askBuyCoach) {
      return;
    }
    if (e.detail.text === '已约') {
      this.setData({
        page: 'show rdv'
      }, () => {
        let t = this.selectComponent('#showdeal');
        t.requestList();
      })
    } else {
      this.setData({
        page: 'make rdv'
      })
    }
  },
  sumbit: function (e) { // 提交按钮
    if (this.data.optionDirty) {
      let list = [];
      for (let i in this.data.kechengbiao) {
        const p = this.data.kechengbiao[i];
        if (p.status.toString() === '1' && p.choose === this.data.userSubject) {
          list.push(p);
        }
      }
      this.setData({
        checkout: true,
        chooseArray: list,
      });
    } else {
      this.setData({
        notionText: '至少选择一个课时',
      })
      setTimeout(() => {
        this.setData({
          notionText: '确认选课',
        })
      }, 1000)
    }
  },
  closeModalFunc: function (e) {
    this.setData({
      cancelRdvModal: false,
    })
  },
  yesFun: function (e) {
    this.setData({
      cancelRdvModal: false,
    })
  },
  closeCheckOut: function (e) {
    this.setData({
      checkout: false,
    })
  },
  cTime: function (e) { // 修改时间状态
    // console.log(e.detail.id);
    const targetProperty = 'cour' + this.data.activeDate + 'id' + e.detail.id;
    let tmp = this.data.kechengbiao;
    let _target = tmp[targetProperty];
    if (!_target) {
      return;
    }
    if (_target.choose !== 'n') {
      _target.choose = 'n';
      this.changeTotalDay(-1);
    } else {
      _target.choose = this.data.userSubject;
      this.changeTotalDay(1);
    }
    this.setData({
      kechengbiao: tmp,
      optionDirty: true,
    }, () => {
      this.inputActiveDateBlock();
      this.reduceTime(15);
    })
  },
  changeTotalDay: function (opt) { // 修改某天的数量显示用
    let tmp = this.data.dateStruct;
    if (opt > 0) {
      for (let i of tmp) {
        if (i.date === this.data.activeDate) {
          i.total += 1;
        }
      }
    } else {
      for (let i of tmp) {
        if (i.date === this.data.activeDate) {
          i.total -= 1;
          i.total = i.total > 0 ? i.total : 0;
        }
      }
    }
    this.setData({
      dateStruct: tmp,
    })
  },
  reduceTime(time) { // 倒计时
    if (!this.data.daojishi) {
      this.setData({
        daojishi: time * 60,
      }, () => {
        optReduceTime = setInterval(() => {
          let newTime = this.data.daojishi - 1;
          if (newTime <= 0) {
            wx.redirectTo({
              url: 'rdv',
            })
            return;
          }
          let min = Math.floor(newTime / 60);
          let sec = newTime % 60;
          sec = sec < 10 ? '0' + sec : sec;
          this.setData({
            daojishi: newTime,
            daojishiStr: min + ':' + sec,
          });
        }, 1000);
      })
    }
  },
  setDate: function (e) { // 修改当前日期
    console.log('设置日期', e.detail.date);
    this.setData({
      activeDate: e.detail.date,
    }, () => {
      this.inputActiveDateBlock();
    });
  },
  deleteTime: function (e) { // 删除时间
    const delTime = e.detail.time;
    if (!delTime) { return; }
    let _tmp = this.data.chooseArray;
    _tmp = _tmp.filter(el => {
      return el !== delTime
    })
    // console.log(_tmp);

    // 刷新当日状态
    console.log(this.data.time);
    let newTime = this.data.time;
    const _actDay = this.data.activeDate; // 激活日
    if (delTime.indexOf(_actDay) === 0) { // 删除日期在当前显示
      const _time = (delTime.split('-'))[1];
      for (let i of newTime) {
        console.log(i.time, _time)
        if (i.time === _time) {
          i.choose = 'n';
          break;
        }
      }
    }
    console.log(newTime);
    this.setData({
      chooseArray: _tmp,
      time: newTime,
    });
  },
  payCoursOnline: function (e) {
    // 预防万一清除数据
    this.setData({ waitPayOrderNumber: null });
    const total = e.detail.price;
    let ids = [];
    for (let i of this.data.chooseArray) {
      ids.push(i.courId);
    }
    wx.request({
      url: 'https://www.haitunxueche.com/student/index/bespokenOrder',
      data: {
        ids: ids.toString()
      },
      header: {
        Authorization: getApp().globalData.login.token
      },
      method: 'GET',
      success: (res) => {
        // console.log(res);
        if (res.data.code === 0) {
          // 需要判断是否需要支付，线下学员不需要支付：支付状态1-待支付，2-支付完成
          if (res.data.data.payStatus == 1) {
            this.setData({
              waitPayOrderNumber: res.data.data.orderNumber
            }, () => {
              this.wxPay(res.data.data.orderNumber);
            })
          }else if(res.data.data.payStatus == 2){
            wx.showModal({
              title: '预约成功',
              content: '预约编号： ' + res.data.data.orderNumber,
              showCancel: false,
              confirmText: '关闭',
              confirmColor: '',
            })
          }
        } else {
          this.failModal(res.data);
        }
      },
      fail: function (res) {
        this.failModal(res);
      },
      complete: function (res) {
        wx.hideLoading();
      },
    })
  },
  failModal(d) {
    wx.showModal({
      title: '错误',
      content: JSON.stringify(d),
      showCancel: false,
      confirmText: '关闭',
      confirmColor: '#fe2742',
    })
  },
  wxPay: function (orderNumber) { // 调用微信支付
    wx.showLoading({
      title: '',
      mask: true,
    })
    wx.request({
      url: 'https://www.haitunxueche.com/pay/wxPay',
      data: {
        orderNum: orderNumber,
      },
      header: {
        Authorization: getApp().globalData.login.token
      },
      method: 'GET',
      success: (res) => {
        if (res.data.code === 0) {
          const pay = {
            nonceStr: res.data.data.nonceStr,
            packageStr: res.data.data.packageStr,
            paySign: res.data.data.paySign,
            signType: res.data.data.signType,
            timeStamp: res.data.data.timeStamp,
          };
          this.sendPayRequest(pay);
        }
        else {
          this.failModal(res.data);
          this.cancelOrderUnpay();
        }
      },
      fail: function (res) {
        this.failModal(res.data);
        this.cancelOrderUnpay();
      },
      complete: function (res) {
        wx.hideLoading();
      },
    })
  },
  sendPayRequest: function (pay) {
    wx.showLoading({
      title: '',
      mask: true,
    })
    wx.requestPayment({
      timeStamp: pay.timeStamp,
      nonceStr: pay.nonceStr,
      package: pay.packageStr,
      signType: pay.signType,
      paySign: pay.paySign,
      success: (res) => {
        console.log('支付成功', res);
        this.paySucess(res);
      },
      fail: (res) => {
        console.log('支付失败', res);
        wx.showToast({
          title: '支付失败:' + JSON.stringify(res.data),
          icon: 'none',
          duration: 4000,
          mask: true,
        })
        this.cancelOrderUnpay();
      },
      complete: (res) => {
        wx.hideLoading();
      },
    })
  },
  paySucess: function (res) {
    if (res.errMsg === "requestPayment:ok") {
      this.setData({
        checkout: false,
      }, () => {
        clearInterval(optReduceTime);
        this.setData({
          daojishi: null,
          daojishiStr: '15:00',
          checkout: false,
          chooseArray: [],
          notionText: '确认选课',
        })
        wx.showModal({
          title: '约课成功',
          content: '合理安排时间，准时上课哟！',
          showCancel: false,
          confirmText: '确定',
          confirmColor: '',
          success: (res) => {
            // 重新恢复状态      
            this.firstStep();
          },
          fail: function (res) { },
          complete: function (res) { },
        })
      })
    }
  },
  cancelOrderUnpay() { // 取消未能支付的订单
    let orderNum = this.data.waitPayOrderNumber;
    if (!orderNum) { return }
    wx.request({
      url: 'https://www.haitunxueche.com/student/index/closeOrder',
      data: {
        orderNumber: orderNum,
      },
      header: {
        Authorization: getApp().globalData.login.token,
      },
      method: 'GET',
      success: function (res) {
        if (res.data.code === 0) {
          console.log('取消未支付订单：' + orderNum);
        }
      },
      fail: function (res) { },
      complete: function (res) { },
    })
  },
  finishsb1: function () {
    // 完成科目1,需要重新获取班级信息
    reloadStudy(this.onShow);
  },
  filterDeal(e) {
    const filter = e.currentTarget.dataset.filter;
    if (filter === this.data.filterDeal) {
      return;
    }
    if (filter === 'time') {
      this.setData({
        filterDeal: 'time',
      })
    } else {
      this.setData({
        filterDeal: 'order',
      })
    }
    const componentDeal = this.selectComponent('#showdeal');
    componentDeal.orderList();
  }
})